package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExeptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handlerSQLConstraintException(SQLIntegrityConstraintViolationException ex) {
        String message = ex.getMessage();
        log.error(message);
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String s = split[2] + "已存在";
            return R.error(s);
        }
        return R.error("数据异常!!");
    }

    @ExceptionHandler(CustomException.class)
    public R exceptionHandler(CustomException ex){
        log.info(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
